package com.basic.framework.filter;


import com.basic.common.utils.JsonUtils;
import com.basic.framework.filter.params.HttpServletRequestCopier;
import com.basic.framework.filter.params.HttpServletResponseCopier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * @author Administrator
 */
public class WatchDogFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(WatchDogFilter.class);

    private static final String COMMA = ".";
    private static final String POST = "POST";
    private static final String GET = "GET";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
            throw new ServletException("not a HTTP request");
        }
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        final String uri = httpRequest.getRequestURI();

        HttpServletRequestCopier requestCopier = new HttpServletRequestCopier(httpRequest);
        HttpServletResponseCopier responseCopier = new HttpServletResponseCopier(httpResponse);

        byte[] requesteCopy = requestCopier.getCopy();
        String reqJson = new String(requesteCopy, httpRequest.getCharacterEncoding());

        if(LOG.isDebugEnabled()){
            final String requestAddress = httpRequest.getRemoteHost();
            LOG.debug("request from {}:{}", requestAddress, uri);
        }

        if(uri.contains(COMMA)){
            LOG.debug("#######有后缀的请求不做处理，直接放行#####");
            filterChain.doFilter(requestCopier, responseCopier);
            responseCopier.flushBuffer();
            return;
        }

        if (POST.equalsIgnoreCase(httpRequest.getMethod())) {
            if (LOG.isDebugEnabled()) {
                try {
                    LOG.debug("original post request json：\n{}", reqJson);
                    LOG.debug("post request json：\n{}", JsonUtils.jsonFormatter(reqJson));
                } catch (Exception e) {
                    LOG.warn("wrong request json format!! \n{}", reqJson);
                }
            }
        }else if (GET.equalsIgnoreCase(httpRequest.getMethod())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("get request parameters({})：\n{}", uri, httpRequest.getQueryString());
            }
        }

        filterChain.doFilter(requestCopier, responseCopier);

        responseCopier.flushBuffer();
        byte[] responseCopy = responseCopier.getCopy();
        String repJson = new String(responseCopy, httpResponse.getCharacterEncoding());

        if (repJson == null || repJson.isEmpty()) {
            LOG.warn("response json is null or empty (response json = {})", repJson);
        }

        if (LOG.isDebugEnabled()) {
            try {
                LOG.debug("response json(request={})：\n{}", uri, JsonUtils.jsonFormatter(repJson));
            } catch (Exception e) {
                LOG.warn("wrong response json format!! response json = \n{}", repJson);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
